package br.com.Bolao.application.util;

import br.com.Bolao.application.dao.usuarios.UsuarioDAO;
import br.com.Bolao.model.Usuario;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.servlet.ContextualHttpServletRequest;
import org.jboss.seam.web.AbstractResource;

/**
 *
 * @author frederico.cruz
 */
@Scope(ScopeType.APPLICATION)
@Name("validaEmail")
@BypassInterceptors
public class EmailServlet extends AbstractResource {

    @Override
    public String getResourcePath() {
        return "/validaEmail";
    }

    @Override
    public void getResource(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        new ContextualHttpServletRequest(request) {

            @Override
            public void process() throws IOException {
                doWork(request, response);
            }
        }.run();
    }

    private void doWork(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String codigo = request.getParameter("codigo");
        String nome = request.getParameter("login");

        UsuarioDAO usuarioDAO = (UsuarioDAO) Component.getInstance("usuarioDAO");
        Usuario usuario = usuarioDAO.obterPorUsuario(nome);
        String idCriptografado = CriptografiaSHA.criptografar(usuario.getIdUsuario().toString());
        if (codigo == null || codigo.equals("")) {
            try {
                response.sendRedirect("http://mbsolutions.com.br/bolao/principal.jsf");
            } catch (IOException ex) {
                Logger.getLogger(EmailServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (codigo.equals(idCriptografado)) {
            usuario.setEmailConfirmado(true);
            usuarioDAO.salvar(usuario);
            response.sendRedirect("http://mbsolutions.com.br/bolao/protected/usuarios/confirmacao_cadastro.jsf");
        } else {
        }
    }
}
